package com.lp.multi.lock;

import java.util.concurrent.TimeUnit;

/**
 * @author: lp
 * @create: 2021-06-26 21:05
 * @description: 八锁现象4
 * 两把锁(不同调用者对象，互不影响)
 * 执行结果:
 * B:send video
 * A:send msg
 */
public class ELock {
    public static void main(String[] args) {
        Phone4 phone1 = new Phone4();
        Phone4 phone2 = new Phone4();
        new Thread(()->{
            phone1.sendMsg();
        },"A").start();

        try {
            //主线程sleep,B线程未获取锁前，确保A线程获取了锁
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            phone2.call();
        },"B").start();
    }
}

class Phone4{

    //synchronized修饰普通方法，锁定的是方法的调用对象,谁先调用，谁先拿到锁
    public synchronized void sendMsg(){
        try {
            //sleep不会释放锁，时间到后，代码继续执行
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+":"+"send msg");
    }

    public synchronized void call(){
        System.out.println(Thread.currentThread().getName()+":"+"call msg");
    }


}